const express = require('express')
const userModel = require('../model/model')
const jwt = require('jsonwebtoken')
const bodyParser = require('body-parser');

const router = express.Router()



router.use(bodyParser.json());

// 支付宝的商户参数（你需要从支付宝开放平台获取）
const ALIPAY_CONFIG = {
    appId: '9021000142622638',
    privateKey: 'MIIEowIBAAKCAQEAqYEXrapi3zsiH9RJnDyfAmd5Q2b6ZKDk3m8kEfu0s0c049Iyyr+VCqpAtNMsizEEx/rEiWbnRJlUx/fyrXImsKIA9ynCOMRmFP+VBANW8HBXM9OkCaKZVdsUyo+8/pUC/Q05mHSTj5FBNJkBy8SICIpLMCxLULsbbnAZbMx+qsD6R+QCOL7lVlSBD+6GFwv4NkKJom1Ez9HA9/LXE26qOWbGqcGzMrNxmezrVVZcwgWkbALrpmF2I8nQpT1TqW3XHGvHolO0jTgNoiNcsfxPElApE2NzgH/q+nuqsb9XYS62bMMSLieRU52fHfvnNrqkKsUzAJtPIgsONZHjWbVzKQIDAQABAoIBAQCj1w7/I2nMYokagQThysrb9Q6GcxxmdgqjYoRYCZdhjtt1trC3vzUeCPDgmBo/NJNthVvBgEDc0uTbITRmKKdzJjSOs8NzQYt2kpEEPwIjCEOR6eluEsfp8AiJvyQsY/ZuiQD59vzG0d1YLOlKf94JezswBjCKiUD7n8lDm+p3utW1ajo5X2H12GW636DsPz3lwfGIevZnZFh3gJkaPRipO/kj4dUFXSt09qXt37AJHhZAyPpQlqyzAegSZ81CrDS3k9Hh8rGkOVWE6EFrofx6nLafKQeoLJhlaDhLiG1/3vvp3fF/ni9KikvcygbqTzWBYLqRLOavwnXmXT48TQOxAoGBAPebMdq9qovJr1yAVGA5p8o/ac+5fVvL4hopVuD5XVNiq8/2fWGjk37RkcmIAAEz8G5EuSsqc9L9et7WqpECWgGQEho/KCSpWd+NcY+awCx5DvjM31iB67gyCEDi4KD+cIddblvo3FCsM4vuZohbO4OT22JklAqfy+dNCIzUWFLdAoGBAK9AGqyRe0yC7rxCeUgIsD0wBMAPF6wg9AVO0SyBbO4c6W+0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    notifyUrl: 'http://127.0.0.1:3000/alipay-notify', // 支付结果异步通知地址
};

// 创建订单并生成支付宝支付参数
router.get('/create-order', async (req, res) => {
  try {
    const orderData = {
      out_trade_no: 'order_id_123456', // 商户订单号，唯一
      subject: 'Test Product', // 订单标题
      total_amount: '0.01', // 订单总金额，单位为元
      body: 'This is a test product', // 订单描述
      timeout_express: '30m', // 订单超时时间
      notify_url: ALIPAY_CONFIG.notifyUrl, // 支付结果通知 URL
    };

    // 生成订单的签名（假设你已经根据支付宝文档生成签名）
    const orderInfo = generateAlipayOrderInfo(orderData, ALIPAY_CONFIG);

    // 将订单信息返回给前端
    res.json({ orderInfo });
  } catch (error) {
    console.error('Error creating order:', error);
    res.status(500).json({ error: 'Failed to create order' });
  }
});

// 生成支付宝订单信息的函数（示例）
function generateAlipayOrderInfo(orderData, config) {
  // 这里你需要根据支付宝文档签名订单
  // 伪代码示例，实际使用时请参考支付宝的官方文档进行签名操作
  const orderInfo = `partner="${config.appId}"&out_trade_no="${orderData.out_trade_no}"&subject="${orderData.subject}"&total_amount="${orderData.total_amount}"&body="${orderData.body}"&timeout_express="${orderData.timeout_express}"&notify_url="${orderData.notify_url}"&_input_charset="utf-8"`;

  // 签名（伪代码）
  const signedOrderInfo = signOrderInfo(orderInfo, config.privateKey);
  return signedOrderInfo;
}

// 签名订单信息（伪代码）
function signOrderInfo(orderInfo, privateKey) {
  // 使用私钥对订单信息进行签名
  return orderInfo + '&sign="signed_value"';
}

// 支付宝支付结果回调
router.post('/alipay-notify', (req, res) => {
  // 支付宝会向该接口发送支付结果通知
  // 你需要验证签名，确保支付结果的真实性

  const paymentResult = req.body;
  // 验证签名（伪代码）
  const isValid = verifyAlipaySignature(paymentResult, ALIPAY_CONFIG.alipayPublicKey);
  
  if (isValid) {
    // 处理支付成功的逻辑
    console.log('支付成功', paymentResult);
    res.status(200).send('success');
  } else {
    // 验证失败
    res.status(400).send('failure');
  }
});

// 验证支付宝签名（伪代码）
function verifyAlipaySignature(paymentResult, alipayPublicKey) {
  // 这里你需要验证支付宝的签名
  return true;
}




module.exports = router